<?php

class Courses {
	function __construct() {
	}

	function getCourseList() {
		global $page_handler;

		$cdata = $page_handler->myCourses();
		$cpath = '/html/body/form/table/tr[2]/td[3]/table/tr[4]/td/div/div/table[2]/tr/td/table/tr/td/table/tr/td/table/tr';
		$clist = xPathify($cdata, $cpath);

		$results      = array();
		$extra_course = false;
		$clist_length = $clist->length;
		$course_row   = 0;
		for ($i = 3; $i < $clist_length; $i++) {
			if (strpos($clist->item($i)->nodeValue, "Valda kurser utanför mina studieplaner")) {
				$i += 2;
				$extra_course = true;
				$course_row   = 0;
			}

			if ($i % 2 == 1) {
				$ccode       = xPathify($cdata, $cpath . '['. ($i + 1) . ']/td/span');
				$course_code = $ccode->item(0)->getAttributeNode('onclick')->nodeValue;
				$course_code = preg_split("/[a-zA-Z',:_()]+/", $course_code);

				$course = $clist->item($i)->nodeValue;
				preg_match('/[0-9]+\.[0-9]+[ ]+(([^,]+,){1,})/', $course, $course_matches);
				$course = $course_matches[1];
				// Remove trailing ',' from course name
				$course = trim($course, ',');

				$results[] = array(
					'course_code'  => $course_code[1],
					'course_name'  => $course,
					'course_extra' => $extra_course,
					'course_row'   => $course_row++,
				);
			}
		}

		return $results;
	}

	function getExaminationList() {
		global $page_handler;

		$edata = $page_handler->myExaminations();
		$epath = '/html/body/form/table/tr[2]/td[3]/table/tr[4]/td/div/div/table[2]/tr/td/table/tr/td/table/tr[1]/td/table/tr';
		$elist = xPathify($edata, $epath);

		$results = array();
		$row     = 0;
		$elist_length = $elist->length;
		for ($i = 2; $i <= $elist_length; $i++) {
			$exam_path = $epath . "[$i]/td";
			$exam      = xPathify($edata, $exam_path);

			$examdate  = trim($exam->item(0)->nodeValue);
			$examdata  = trim($exam->item(1)->nodeValue);
			$active    = trim($exam->item(2)->nodeValue);
			$status    = trim($exam->item(3)->nodeValue);
			$completed = trim($exam->item(4)->nodeValue);
			$enroll    = trim($exam->item(5)->nodeValue);
			$drop      = false;

			$name = explode ("[",$examdata);
			$name = preg_replace('/\h+/', ' ', $name[0]);
			$name = preg_replace('/\v{3,}/', ' ', $name);

			if (stristr($enroll, 'Anmäl')) {
				$enroll = true;
			}
			else {
				$enroll = false;
				if (stristr($status, 'Anmäld')) {
					$drop = true;
				}
			}

			$results[] = array(
				'exam_date'      => $examdate,
				'exam_name'      => $name,
				'exam_active'    => $active,
				'exam_status'    => $status,
				'exam_completed' => $completed,
				'exam_enroll'    => $enroll,
				'exam_drop'      => $drop,
				'exam_row'       => $row++
			);
		}

		return $results;
	}

	function getCourse($course_id) {
		global $page_handler;

		$course_data = $page_handler->getCourse($course_id);

		$course_path = '/html/body/form/table/tr[2]/td[3]/table/tr[4]/td/div/div/table[1]/tr[2]/td[2]/table/tr/td';
		$course_page = xPathify($course_data, $course_path);

		// Remove newlines and tabs
		trimNodeValues($course_page);

		$course             = array();
		$course_page_length = $course_page->length;

		// Loop through table content and find relevant information
		for ($i = 0; $i < $course_page_length; $i++) {
			$data = $course_page->item($i)->nodeValue;

			if (strstr($data, 'Kurs:')) {
				$i++;
				$course['info'] = $course_page->item($i)->nodeValue;
			}
			else if (strstr($data, 'Målsättning:')) {
				$i++;
				$course['goal'] = $course_page->item($i)->nodeValue;
			}
			else if (strstr($data, 'Kursens hemsida:')) {
				$i++;
				$course['page'] = $course_page->item($i)->nodeValue;
			}
			else if (strstr($data, 'Tidpunkt:')) {
				$i++;
				$course['time'] = $course_page->item($i)->nodeValue;
			}
		}
		// Extract course code, version, name and studypoints from $course['info']
		$regex        = '/([0-9]+\.[0-9]+)[^(]*\(([^)]+)\)([^(]+)\(([^)]+)\)/';
		$info_matches = array();
		preg_match($regex, $course['info'], $info_matches);
		
		$course['code']    = $info_matches[1];
		$course['version'] = $info_matches[2];
		$course['name']    = $info_matches[3];
		$course['sp']      = $info_matches[4];

		return $course;
	}

	function getExaminationInfo() {
	}

	function searchCoursesOrExams($type) {
			global $page_handler;
			
			$cur_year = getSchoolYear();
			
			$calls = array();
			$calls['courseSearchCriteria.yearCode'] = $cur_year;
			
			if(preg_match("/^(\d{5,6}).(\d)$/", $_POST['searchF'])) $calls['courseCode'] = $_POST['searchF'];
			else $calls['courseSearchCriteria.freetext'] = $_POST['searchF'];
			
			$calls = array('courseSearchCriteria.freetext' => ''.$_POST['searchF'].'', 'courseSearchCriteria.yearCode' => ''.$cur_year.'');
			if ($type == 'course') $html = $page_handler->searchCourse($calls);
			else $html = $page_handler->searchExamination($calls);
			
		
		$pages=null;
		
		$links = xPathify($html, '/html/body/form/table/tr[2]/td[3]/table/tr[4]/td/div/div/div/table/tr[2]/td[2]/table[1]/tr[2]/td/span')->length;
        
		if ($links>0 && $pages==null){
            $pages = str_replace("'", "", explode(',',(xPathify($html, '/html/body/form/table/tr[2]/td[3]/table/tr[4]/td/div/div/div/table/tr[2]/td[2]/table[1]/tr[2]/td/span['.$links.']')->item(0)->getAttribute('onclick'))));
            $pages = $pages[1];

        }
		
        $courses = xPathify($html, '/html/body/form/table/tr[2]/td[3]/table/tr[4]/td/div/div/div/table/tr[2]/td[2]/table[1]/tr[1]/td/table/tr');
		
		
		$results = array();
		
        for ($i=1; $i<$courses->length ;$i++) {

            $course = $courses->item($i)->nodeValue;
			$regex = '/([0-9]+\.[0-9]+)(.+)\(([0-9]+\.[0-9] sp)\)(([0-9]{4}-[0-9]{4})-[a-z]+ ([0-9]+))?[ ]*([^ ]*)/';
			preg_match($regex, $course, $info_matches);		
			
			if ($type == 'course') {
				$results[] = array(
					'code' => $info_matches[1],
					'name' => $info_matches[2],
					'sp' => $info_matches[3],
					'years' => $info_matches[5],
					'version' => $info_matches[6],
					'type' => $info_matches[7]
				);
			}
			else {
				$results[] = array(
					'code' => $info_matches[1],
					'name' => $info_matches[2],
					'sp' => $info_matches[3],
					'type' => $info_matches[4]
				);
			}
			
		}
			
		return $results;
	}

	function searchExaminations() {
	
	}

	function removeCourse($page, $row) {
		global $page_handler;

		if (!is_numeric($page) || !is_numeric($row)) {
			return false;
		}

		return $page_handler->removeCourse($page, $row);
	}

	function dropCourse() {
	}

	function removeExamination($row) {
		if (!is_numeric($row)) {
			return false;
		}

		global $page_handler;

		return $page_handler->removeExamination($row);
	}

	function enrollExamination($row) {
		if (!is_numeric($row)) {
			return false;
		}

		global $page_handler;

		return $page_handler->enrollExamination($row);
	}

	function dropExamination($row) {
		if (!is_numeric($row)) {
			return false;
		}

		global $page_handler;

		return $page_handler->dropExamination($row);
	}
}

